import base64,pickle
from django_redis import get_redis_connection


def merge_carts_cookies_redis(request, user, response):
    """合并购物车(以cookies为主)"""

    # 获取cookies中的购物车数据,并判断是否有购物车数据
    carts_str = request.COOKIES.get('carts')

    # 判断cookies中的购物车数据是否存在
    # 如果不存在,不需要合并
    if not carts_str:
        return response


    # 将 carts_str字符串 转 bytes字符串
    cookie_carts_str_bytes = carts_str.encode()
    # 将carts_str_bytes字符串 转 cookie_carts_dict_bytes字典
    cookie_carts_dict_bytes = base64.b64decode(cookie_carts_str_bytes)
    # 将cookie_carts_dict_bytes字典 转 cookie_carts_dict数据字典
    cookie_carts_dict = pickle.loads(cookie_carts_dict_bytes)

    #如果存在, 需要合并

    # 准备新的数据容器: 保存新的sku_id: count selected unselected
    new_cart_dict= {}
    new_selected_add = []
    new_selected_rem = []

    # 遍历cookis中的购物车数据
    for sku_id,cookie_dict in cookie_carts_dict.items():
        new_cart_dict[sku_id] = cookie_dict['count']

        if cookie_dict['selected']:
            new_selected_add.append(sku_id)
        else:
            new_selected_rem.append(sku_id)

    #根据新的数据结构,合并到redis
    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()
    pl.hmset('carts_%s' % user.id, new_cart_dict)
    if new_selected_add:
        pl.sadd('selected_%s' % user.id, *new_selected_add)
    if new_selected_rem:
        pl.srem('selected_%s' % user.id, *new_selected_rem)
    pl.execute()

    # 删除cookie
    response.delete_cookie('carts')

    return response